/*
 * Copyright (c) 2024-2025 iSOFT INFRASTRUCTURE SOFTWARE CO., LTD.
 * easyAda is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */

#include <stdlib/assert.h>
#include <stdlib/string.h>
#include <core/task.h>
#include <uapi/ipcbuffer.h>

void ipcbuffer_partial_transfer(tcb_t *dst, tcb_t *src, unsigned long tag)
{
    ipcbuffer_t *dbuf;
    ipcbuffer_t *sbuf;
    unsigned int len;

    unsigned long *dmsgs;
    unsigned long *smsgs;

    assert(tcb_is_valid(dst) && tcb_is_valid(src));

    dbuf = task_get_ipcbuffer(dst);
    sbuf = task_get_ipcbuffer(src);

    // the first 2 words will be transferred through registers, ignore them
    dmsgs = &((ipcbuffer_get_msgs(dbuf))[2]);
    smsgs = &((ipcbuffer_get_msgs(sbuf))[2]);
    len   = msgtag_get_len(tag) - 2U;

    if (msgtag_get_len(tag) <= 2U) {
        return;
    }

    if (len <= (unsigned int)(IPC_MAX_MSGWORDS - 2)) {
        (void)memcpy(dmsgs, smsgs, len * sizeof(unsigned long));
    } else {
        dprintf("Warning: too many messages words to copy!");
    }
}

void ipcbuffer_regs_transfer(tcb_t *dst, unsigned long tag, unsigned long m0, unsigned long m1)
{
    ipcbuffer_t *buf = task_get_ipcbuffer(dst);

    assert(tcb_is_valid(dst));
    ipcbuffer_save(buf, tag, m0, m1);
}

void ipcbuffer_full_transfer(tcb_t *dst, tcb_t *src)
{
    unsigned long *msgs;
    unsigned long  tag;
    ipcbuffer_t   *f;

    assert(tcb_is_valid(dst) && tcb_is_valid(src));

    f    = task_get_ipcbuffer(src);
    msgs = ipcbuffer_get_msgs(f);
    tag  = ipcbuffer_get_tag(f);

    ipcbuffer_regs_transfer(dst, tag, msgs[0], msgs[1]);
    if (ipcbuffer_get_msglen(f) > 2U) {
        ipcbuffer_partial_transfer(dst, src, tag);
    }
}
